package com.gzhryc.net_marketing.cloud.micro.api.controllers.cloud;

import com.gzhryc.common.api.DefaultAPICodeConstants;
import com.gzhryc.common.api.DefaultAPIResponse;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.net_marketing.api.protocol.order.*;
import com.gzhryc.net_marketing.cloud.business.dao.db.CloudGoodsPayOrder;
import com.gzhryc.net_marketing.cloud.business.dao.db.MarketProjectApp;
import com.gzhryc.net_marketing.cloud.business.dao.db.MarketSupplier;
import com.gzhryc.net_marketing.cloud.business.services.CloudGoodsPayOrderService;
import com.gzhryc.net_marketing.cloud.business.services.MarketProjectAppService;
import com.gzhryc.net_marketing.cloud.business.services.MarketSupplierService;
import com.gzhryc.net_marketing.cloud.notice.SupplyChainAPIService;
import com.gzhryc.net_marketing.core.enums.GoodsOrderEnum;
import com.gzhryc.net_marketing.core.notice.order.ConfirmOrderNotice;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;

public class CloudGoodsOrderAPIController {

    static Logger log = Logger.getLogger(CloudGoodsOrderAPIController.class);

    @Route(value = { "/market/cloud_api/v1/goods/order/create.do" })
    public CreateSupplierGoodsOrderResponse createGoodsOrder(HttpServletRequest request) {
        CreateSupplierGoodsOrderResponse apiResp = new CreateSupplierGoodsOrderResponse(DefaultAPICodeConstants.EXECUTE_ERROR, "创建订单失败");
        CreateSupplierGoodsOrderRequest apiReq = WebUtils.getJsonRequest(request, CreateSupplierGoodsOrderRequest.class);
        if (apiReq != null && apiReq.getBody().getProjectId() != null && StringUtils.isNotBlank(apiReq.getBody().getGoodsCode())
                && apiReq.getBody().getGoodsCount() != null) {
            log.info("创建云订单，请求：{{0:json}}",apiReq);
            try {
                CreateSupplierGoodsOrderResponse tempResp = CloudGoodsPayOrderService.self().add(apiReq);
                if(tempResp != null){
                    apiResp = tempResp;
                }
            } catch (LogicException e) {
                apiResp.setCode(DefaultAPICodeConstants.EXECUTE_ERROR, e.getMessage());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        } else {
            log.error("创建云订单时参数错误，请求参数：{{0:json}}", apiReq);
            apiResp.setCode(DefaultAPICodeConstants.EXECUTE_ERROR, "参数错误");
        }
        return apiResp;
    }

    @Route(value = { "/market/cloud_api/v1/goods/order/get.do" })
    public GetSupplierGoodsOrderResponse getGoodsOrder(HttpServletRequest request) {
        GetSupplierGoodsOrderResponse apiResp = new GetSupplierGoodsOrderResponse(DefaultAPICodeConstants.EXECUTE_ERROR, "获取订单失败");
        GetSupplierGoodsOrderRequest apiReq = WebUtils.getJsonRequest(request, GetSupplierGoodsOrderRequest.class);
        if (apiReq != null && StringUtils.isNotBlank(apiReq.getBody().getTradeNo())) {
            CloudGoodsPayOrder supplierGoodsOrder = CloudGoodsPayOrderService.self().getByTradeNo(apiReq.getBody().getTradeNo());
            if(supplierGoodsOrder == null){
                supplierGoodsOrder = CloudGoodsPayOrderService.self().getBySupplierTradeNo(apiReq.getBody().getTradeNo());
            }
            if(supplierGoodsOrder != null){
                MarketSupplier supplier = MarketSupplierService.self().getById(supplierGoodsOrder.getSupplierId());
                if (supplier != null) {
                    apiReq.getBody().setTradeNo(supplierGoodsOrder.getSupplierTradeNo());       //供应商订单
                    GetSupplierGoodsOrderResponse tempResp = SupplyChainAPIService.self().getGoodsOrder(supplier.getId(), apiReq);
                    if (tempResp != null) {
                        tempResp.getBody().setTradeNo(supplierGoodsOrder.getTradeNo());     //商城项目订单
                        return tempResp;
                    }
                } else {
                    log.error("供货商{{0}}不存在", supplierGoodsOrder.getSupplierId());
                }
            }
        }else{
            apiResp.setMsg("参数错误");
        }
        return apiResp;
    }

    /**
     * 供应商确认订单
     * @param request
     * @return
     */
    @Route(value = { "/market/cloud_api/v1/order/goods/confirm.do" })
    public DefaultAPIResponse confirmGoodsOrder(HttpServletRequest request) {
        DefaultAPIResponse apiResp = new DefaultAPIResponse(DefaultAPICodeConstants.EXECUTE_ERROR, "订单确定失败");
        ConfirmGoodsOrderRequest apiReq = WebUtils.getJsonRequest(request, ConfirmGoodsOrderRequest.class);
        if (apiReq != null && StringUtils.isNotBlank(apiReq.getBody().getTradeNo()) && apiReq.getBody().getConfirmState() != null) {
            CloudGoodsPayOrder cloudGoodsPayOrder = CloudGoodsPayOrderService.self().getByTradeNo(apiReq.getBody().getTradeNo());
            if(cloudGoodsPayOrder == null){
            	cloudGoodsPayOrder = CloudGoodsPayOrderService.self().getBySupplierTradeNo(apiReq.getBody().getTradeNo());
            }
            if (cloudGoodsPayOrder != null) {
            	 MarketProjectApp marketProject = MarketProjectAppService.self().getById(cloudGoodsPayOrder.getProjectId());
            	 if(marketProject != null) {
            		 ConfirmOrderNotice.Body notice = new ConfirmOrderNotice.Body();
            		 notice.setProjectTradeNo(cloudGoodsPayOrder.getTradeNo());     //商城项目订单
            		 notice.setNote(apiReq.getBody().getNote());
            		 if(apiReq.getBody().getConfirmState()) {
            			 notice.setSupplyState(GoodsOrderEnum.SupplyState.FinishConfirm.index());
            		 }else {
            			 notice.setSupplyState(GoodsOrderEnum.SupplyState.UnableToSupply.index());
            		 }
            		 
            		 if(CloudGoodsPayOrderService.self().updateSupplyState(cloudGoodsPayOrder.getTradeNo(),
            				 notice.getSupplyState())) {
            			 //NOTO 通知商城项目
            			 
            		 }
            	 }
            }
        }else{
            apiResp.setMsg("参数错误");
        }
        return apiResp;
    }

    @Route(value = { "/market/cloud_api/v1/order/goods/state/update.do" })
    public DefaultAPIResponse updateGoodsOrderState(HttpServletRequest request) {
        DefaultAPIResponse apiResp = new DefaultAPIResponse(DefaultAPICodeConstants.EXECUTE_ERROR, "订单状态同步失败");
        UpdateGoodsOrderStateRequest apiReq = WebUtils.getJsonRequest(request, UpdateGoodsOrderStateRequest.class);
        if (apiReq != null && StringUtils.isNotBlank(apiReq.getBody().getTradeNo())) {
            CloudGoodsPayOrder supplierGoodsOrder = CloudGoodsPayOrderService.self().getByTradeNo(apiReq.getBody().getTradeNo());
            if(supplierGoodsOrder == null){
                //供货商确认订单
                supplierGoodsOrder = CloudGoodsPayOrderService.self().getBySupplierTradeNo(apiReq.getBody().getTradeNo());
            }
            if (supplierGoodsOrder != null) {
                if(GoodsOrderEnum.State.WaitReceive.index().equals(apiReq.getBody().getState())){
                    if(CloudGoodsPayOrderService.self().updateState(supplierGoodsOrder.getTradeNo(),GoodsOrderEnum.State.WaitReceive.index())){
                        //触发通知
                        MarketProjectApp marketApp = MarketProjectAppService.self().getById(supplierGoodsOrder.getProjectId());
                        if(marketApp != null){
                            
                        }else {
                            log.error("商城项目{{0}}不存在", supplierGoodsOrder.getProjectId());
                        }
                    }
                }else if(GoodsOrderEnum.State.WaitEvaluate.index().equals(apiReq.getBody().getState())){
                    if(CloudGoodsPayOrderService.self().updateState(supplierGoodsOrder.getTradeNo(),GoodsOrderEnum.State.WaitEvaluate.index())){
                        //触发通知
                        MarketSupplier networkMarketApp = MarketSupplierService.self().getById(supplierGoodsOrder.getSupplierId());
                        if (networkMarketApp != null) {
                            
                        }else {
                            log.error("供货商{{0}}不存在", supplierGoodsOrder.getProjectId());
                        }
                    }
                }
            }
        }else{
            apiResp.setMsg("参数错误");
        }
        return apiResp;
    }

    @Route(value = { "/market/cloud_api/v1/order/address/update.do" })
    public UpdateGoodsOrderAddressResponse updateGoodsOrderAddress(HttpServletRequest request) {
        UpdateGoodsOrderAddressResponse apiResp = new UpdateGoodsOrderAddressResponse(DefaultAPICodeConstants.EXECUTE_ERROR, "修改订单收货失败");
        UpdateGoodsOrderAddressRequest apiReq = WebUtils.getJsonRequest(request, UpdateGoodsOrderAddressRequest.class);
        if (apiReq != null && StringUtils.isNotBlank(apiReq.getBody().getTradeNo())) {
            CloudGoodsPayOrder supplierGoodsOrder = CloudGoodsPayOrderService.self().getByTradeNo(apiReq.getBody().getTradeNo());
            if(supplierGoodsOrder == null){
                //供货商确认订单
                supplierGoodsOrder = CloudGoodsPayOrderService.self().getBySupplierTradeNo(apiReq.getBody().getTradeNo());
            }
            if (supplierGoodsOrder != null) {
                MarketSupplier supplier = MarketSupplierService.self().getById(supplierGoodsOrder.getSupplierId());
                if (supplier != null) {
                    apiReq.getBody().setTradeNo(supplierGoodsOrder.getSupplierTradeNo());     //供应商订单
                    UpdateGoodsOrderAddressResponse tempResp = SupplyChainAPIService.self().updateGoodsOrderAddress(supplier.getId(), apiReq);
                    if (tempResp != null) {
                        return tempResp;
                    }
                } else {
                    log.error("供货商{{0}}不存在", supplierGoodsOrder.getSupplierId());
                }
            }
        }else{
            apiResp.setMsg("参数错误");
        }
        return apiResp;
    }

}
